<template>
  <CommonPage title="储值管理">
    <template #mid>
      <SearchForm :keyword-search-data="[{ key: 'keywords', label: '卡号' }]">
        <template #extraButtons>
          <a-button type="default" class="mr-2" :loading="downloading" @click="downloadTpl">下载模板</a-button>
          <a-upload
            :accept="acceptExts.join(',')"
            :custom-request="customRequest"
            :before-upload="beforeUpload"
            :show-upload-list="false"
            :disabled="importing"
            @change="change"
          >
            <a-button type="primary" :loading="importing">导入</a-button>
          </a-upload>
        </template>
      </SearchForm>
    </template>
    <SlTable
      :columns="columns"
      row-key="levels"
      :data-source="tableData"
      :pagination="pagination"
      :loading="tableLoading"
    >
      <template #bodyCell="{ column, record }: BodyCellOptions<Partial<StoreValueItem>>">
        <div v-if="column.key === 'oper'">
          <a v-if="record.status !== StoreValueStatus.frozen" class="mr-2 text-red-400" @click="handleFrozen(record)">
            冻结
          </a>
          <a v-else class="mr-2 text-color-success" @click="handleFrozen(record)"> 解冻 </a>
          <a @click="checkAssume(record)">查看消费</a>
        </div>
      </template>
    </SlTable>
  </CommonPage>
</template>
<script lang="ts" setup>
import { ref, shallowRef } from "vue";
import { useI18n } from "/@/locales/useI18n";
import { useCURD } from "/@/hooks/useCURD";
import { FormItemComponentType, CURDAction, CURDDialogExpose } from "/@/components/CURDDialog/models";
import type { FormItemData, OperItem, ShowCURDModalOptions, CURDModalEvent } from "/@/components/CURDDialog/models";
import { message, UploadProps, type TableProps, type UploadChangeParam, UploadFile } from "ant-design-vue";
import { StoreValueItem, StoreValueStatus } from "/@/api/main/member/models";
import { Api, togggleFreeze } from "/@/api/main/member";
import type { BodyCellOptions } from "/@/types/antd";
import { downloadFile, getLabelByValueFromEnum, handleDateRowRender } from "/@/utils/common";
import req, { getAuthHeaderInfo } from "/@/api/req";
import env from "/@/base/env";
import type { UploadRequestError } from "ant-design-vue/es/vc-upload/interface";
import { getExt } from "/@/utils/file";

const { t } = useI18n();
const acceptExts = [".xlsx", ".xls"];
const columns = ref<TableProps<Partial<StoreValueItem>>["columns"]>([
  {
    title: "导入日期",
    dataIndex: "postTime",
    customRender: handleDateRowRender,
  },
  {
    title: "卡号",
    dataIndex: "cardNo",
  },
  {
    title: "密码",
    dataIndex: "passwd",
  },
  {
    title: "面额",
    dataIndex: "denomination",
  },
  {
    title: "关联日期",
    dataIndex: "associatedTime",
  },
  {
    title: "会员姓名",
    dataIndex: "memberName",
  },
  {
    title: "手机",
    dataIndex: "phone",
  },
  {
    title: "余额",
    dataIndex: "balance",
  },
  {
    title: "状态",
    dataIndex: "status",
    customRender({ text }) {
      return getLabelByValueFromEnum(text, StoreValueStatus, "storeValueStatus");
    },
  },
  {
    title: t("common.oper"),
    key: "oper",
    width: 100,
  },
]);

const { pagination, tableData, tableLoading, reloadTable } = useCURD<StoreValueItem>({
  getPageUrl: Api.storeValuePage,
});

const downloading = ref(false);
async function downloadTpl() {
  window.open("https://zyxgo.xyz/files/2024/12/02/3e565e255d8242e2ae1e271ea1b60f69.xlsx");
  // downloading.value = true;
  // await downloadFile("https://zyxgo.xyz/files/2024/12/02/3e565e255d8242e2ae1e271ea1b60f69.xlsx", "储值卡导入模板");
  // downloading.value = false;
}

const importing = ref(false);
// async function handleImport() {
//   importing.value = true;
// }
const customRequest: UploadProps["customRequest"] = async (options) => {
  const formData = new FormData();
  formData.append("file", options.file);
  importing.value = true;
  const result = await req.post<any>({ data: formData, url: Api.importStoreValue }, { useGlobalLoading: false });
  importing.value = false;
  if (result) {
    options.onSuccess && options.onSuccess(result);
  } else {
    let obj: UploadRequestError = {
      status: 500,
      name: "",
      message: "上传失败",
    };
    options.onError && options.onError(obj);
  }
};

const beforeUpload: UploadProps["beforeUpload"] = (file) => {
  const isLt = file.size / 1024 / 1024 < 10;
  if (!isLt) {
    message.warning(`上传文件大小不能超过10M`);
    return false;
  }
  const ext = getExt(file.name);
  if (!ext || !acceptExts.includes("." + ext)) {
    message.info("请上传excel文件");
    return false;
  }
  return true;
};

const change = (info: UploadChangeParam<UploadFile<any>>) => {
  console.log("========>change", info);
  if (info.file.status === "uploading") {
    importing.value = true;
    return;
  } else if (info.file.status === "done") {
    importing.value = false;
    const res = info.file.response;
    if (res) {
      message.success("上传成功");
      reloadTable();
    } else {
      // message.error("上传失败，请稍候再试");
    }
  } else if (info.file.status === "error") {
    importing.value = false;
    // message.error("上传失败，请稍候再试");
  }
};

async function handleFrozen(record) {
  const re = await togggleFreeze(record.id);
  if (re === undefined) {
    message.success("操作成功");
    reloadTable();
  }
}

function checkAssume(record) {}
</script>
